package com.mq.mqtest.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 消息抵达broker服务器时执行这个函数
     */
    @PostConstruct //对象创建完以后，执行这个方法
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 当前消息的唯一关联数据（消息的唯一ID）
             * @param ack   消息是否成功收到
             * @param cause 如果失败，失败的原因。成功打印时则输出null
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm...===CorrelationData：" + correlationData);
                System.out.println("confirm...===ack:" + ack);
                System.out.println("confirm...===cause：" + cause);
            }
        });

        /**
         * 只要消息未能成功抵达指定队列，就会触发这个失败回调
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             *
             * @param message 投递失败的消息详细信息
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本内容
             * @param exchange 当时这个消息发给哪个交换机
             * @param routingKey 消息的路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange,
                String routingKey) {
                System.out.println("failed msg..." + message);
                System.out.println("failed msg..." + replyCode);
                System.out.println("failed msg..." + replyText);
                System.out.println("failed msg..." + exchange);
                System.out.println("failed msg..." + routingKey);
            }
        });
    }


}